package com.cssw.fyzb.tps.service.res.adapter;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.StorageClass;
import com.cssw.fyzb.tps.config.res.OssConfiguration;

import java.io.ByteArrayInputStream;

/**
 * @author Feng Chen
 */
public class OssAdapter implements ResAdapter {

    private OssConfiguration configuration;

    private OSS ossClient;

    public OssAdapter(OssConfiguration configuration) {
        this.configuration = configuration;
    }

    @Override
    public String upload(String dest, String contentType, byte[] content) {
        PutObjectRequest request = new PutObjectRequest(
                configuration.getBucket(),
                dest,
                new ByteArrayInputStream(content)
        );

        // 设置公共读
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
        metadata.setObjectAcl(CannedAccessControlList.PublicRead);
        request.setMetadata(metadata);

        ossClient.putObject(request);
        return String.format(
                configuration.getUrlFormat(),
                configuration.getBucket(),
                configuration.getRegion(),
                dest
        );
    }

    @Override
    public void start() {
        if (ossClient != null) {
            return;
        }

        ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
        conf.setConnectionTimeout(configuration.getConnectionTimeout());
        conf.setSocketTimeout(conf.getSocketTimeout());

        ossClient = new OSSClientBuilder()
                .build(
                        configuration.getEndpoint(),
                        configuration.getAccessKeyId(),
                        configuration.getAccessKeySecret(),
                        conf
                );
    }

    @Override
    public void close() {
        if (ossClient != null) {
            ossClient.shutdown();
            ossClient = null;
        }
    }
}
